var models = require('../db');
var express = require('express');
const jwt = require('jsonwebtoken');
// var uuid = require('node-uuid');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../sql');

// 连接数据库
var conn = mysql.createConnection(models.mysql);

conn.connect();

// 查询权限列表
router.post('/getPerInfo', (req,res) => {
  var sql = $sql.perInfo.getPerInfo;
  let content = [];
  let isMore = false;// 是否有多个查询参数
  // 姓名
  if(req.body.userId !== ''){
    if (isMore){
      sql += " and "
    }else {
      sql +=" where "
    }
    sql += "userId LIKE ?";
    content.push( "%"+req.body.userId+"%" );
    isMore = true;
  }
  if(req.body.userName !== ''){
    if (isMore){
      sql += " and "
    }else {
      sql +=" where "
    }
    sql += "userName LIKE ?";
    content.push( "%"+req.body.userName+"%" );
    isMore = true;
  }
  if(req.body.permissions !== ''){
    if (isMore){
      sql += " and "
    }else {
      sql +=" where "
    }
    sql += "permissions LIKE ?";
    content.push( "%"+req.body.permissions+"%" );
    isMore = true;
  }
  conn.query(sql, content, function (err, result) {
    var data = JSON.parse(JSON.stringify(result))
    return res.send({
        status: 200,
        msg: "查询成功",
        list: data
      })
  })
});
router.post('/addPerInfo', (req,res) => {
  var sql = $sql.perInfo.addPerInfo;
  conn.query(sql,[req.body.userId, req.body.userName, req.body.permissions], function (err, result) {
    return res.send({
        status: 200,
        msg: "新增成功"
      })
  })
});
router.post('/reducePer', (req,res) => {
  var sql = $sql.perInfo.reducePer;
  conn.query(sql,[req.body.userId,req.body.permissions], function (err, result) {
    return res.send({
        status: 200,
        msg: "删除成功"
      })
  })
});
router.post('/updatePer', (req,res) => {
  console.log(req.body.permissions);
  console.log(req.body.userId);
  var sql = $sql.perInfo.updatePer;
  conn.query(sql,[req.body.permissions,req.body.userId], function (err, result) {
    return res.send({
        status: 200,
        msg: "修改权限成功"
      })
  })
});
router.post('/updatePerPw', (req,res) => {
  var sql = $sql.perInfo.updatePerPw;
  conn.query(sql,[req.body.passWord,req.body.userId], function (err, result) {
    return res.send({
        status: 200,
        msg: "修改密码成功"
      })
  })
});
module.exports = router;
